﻿using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Autofac.Core;
using Autofac.Integration.Mvc;
using Autofac.Integration.Web;
using ForumEngine.Routing;
using ViewServices;

namespace ForumEngine
{
    public class MvcApplication : HttpApplication, IContainerProviderAccessor
    {
        private static IContainerProvider _containerProvider;

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.Add("Applications", new ApplicationRoute(new MvcRouteHandler()));
        }

        protected void Application_Start()
        {
            ViewServicesDatabase.Initialize();

            var builder = new ContainerBuilder();
            builder.RegisterModule<ViewServicesModule>();
            builder.RegisterSource(new ViewRegistrationSource());
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            var container = builder.Build();
            _containerProvider = new ContainerProvider(container);
            ControllerBuilder.Current.SetControllerFactory(new ControllerFactory(ContainerProvider));
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        public IContainerProvider ContainerProvider
        {
            get { return _containerProvider; }
        }
    }
}
